package com.WangNan.mall.controller;

import com.WangNan.mall.entity.Category;
import com.WangNan.mall.entity.Goods;
import com.WangNan.mall.pojo.GoodsQO;
import com.WangNan.mall.service.CategoryService;
import com.WangNan.mall.service.GoodsService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Description:
 * @Author :W.
 * @Date:2025/4/22 15:14
 */
@Slf4j
@Controller
@RequestMapping("admin/goods")
public class GoodsController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private GoodsService goodsService;

    @GetMapping("add")
    public String add(Model model) {
        //查询所有的类别
        List<Category> categories = categoryService.list();
        model.addAttribute("categories", categories);
        return "goods_add";
    }

    @Value("${images.uploadpath}")
    private String uploadPath;

    @PostMapping("add")
    public String add(Goods goods, MultipartFile file, HttpSession session) {
        if (session.getAttribute("manager")==null){
            return "redirect:/admin/login";
        }

        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "");
        File dest = new File(uploadPath + "\\" + newFileName + suffix);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败，请检查上传目录权限或路径配置", e);
        }
        log.debug("Goods:{}", goods);
        goods.setImage("http://localhost:8080/" + newFileName + suffix);
        goodsService.add(goods);
        return "redirect:/admin/goods/listbypage";
    }

//    @GetMapping("list")
//    public String list(Model model){
//        model.addAttribute("goodses", goodsService.findAll());
//        return "goods_list";
//    }

    @GetMapping("listbypage")
    public String listByPage(Integer pageNo, GoodsQO goodsQO, Model model) {
        log.debug("GoodsQO:{}", goodsQO);
        int page = 1;
        if (pageNo != null) {
            page = pageNo;
        }
        model.addAttribute("pageBean", goodsService.findByPage(page, goodsQO));
        List<Category> categories = categoryService.list();
        model.addAttribute("categories", categories);
        //model.addAttribute("goodsQO", goodsQO);

        return "goods_list";
    }

}